package br.com.comandamenu.control;

import java.io.IOException;

import org.jdom2.Document;
import org.jdom2.output.XMLOutputter;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.*;
import org.ksoap2.transport.HttpTransportSE;
import org.ksoap2.transport.HttpsTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.database.Cursor;

public class WSCliente {
	
	private SoapPrimitive retorno;
	private Object msg;

	private static String SOAP_ACTION = ""; 
	private static String METHOD_NAME = "";
	private static String NAMESPACE   = "";
	private static Document PARAMETRO = null;
	private static String URL         = "";
	private static String HOST = "";
	private static String PORTA = "";
	
	public WSCliente(String _NOME_METODO,String _NAMESPACE, Document _PARAMETRO, Context Contexto){		
		SOAP_ACTION = _NAMESPACE + _NOME_METODO;
		METHOD_NAME = _NOME_METODO;
		NAMESPACE   = _NAMESPACE;
		PARAMETRO   = _PARAMETRO;
		try {		
			Banco _bd = new Banco(Contexto);
			Cursor _cursor = null;
			_bd.open();
			_cursor = _bd.consulta("webservice", new String[]{"*"}, "_ID = 1", null, null, null, null, null);
			_cursor.moveToFirst();
			if (_cursor.getCount() > 0){	
				HOST  = _cursor.getString(_cursor.getColumnIndex("WS_URL")).toString().trim();
				PORTA = _cursor.getString(_cursor.getColumnIndex("WS_PORTA")).toString().trim();
				URL = "http://"+HOST+":"+PORTA+ "/soap/IComanda";
			}
			_cursor.close();
			_bd.fechaBanco();	
		} finally { 		
			//
		}
	}
	
	public WSCliente(String _NOME_METODO,String _NAMESPACE){
		SOAP_ACTION = _NAMESPACE + _NOME_METODO;
		METHOD_NAME = _NOME_METODO;
		NAMESPACE   = _NAMESPACE;
	}	
	
	public boolean Execute() throws IOException, XmlPullParserException{	
		
		try{		
			SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
			
			XMLOutputter xmOut = new XMLOutputter();
			
			if (PARAMETRO != null) { 
				Request.addProperty("sReq",xmOut.outputString(PARAMETRO));
			}	
			
			SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			
			soapEnvelope.dotNet = true;
			
			soapEnvelope.setOutputSoapObject(Request);						
									
			HttpTransportSE aht = new HttpTransportSE(URL,3000);						
									
			aht.call("", soapEnvelope);
			
			//retorno = (SoapPrimitive)soapEnvelope.getResponse();
			
			msg = soapEnvelope.getResponse();				
			
			return true;
		}catch(Exception e){
			return false;
		}
	}	
	
	public Object getRetorno(){
		return msg;
	}

}
